<template>
  <div class="container">
    <!-- 左边的信息展示 -->
    <div>
      <!-- 展示头像 -->
      <div>
        <el-row class="demo-avatar demo-basic">
          <el-col :span="12">
            <div class="demo-basic--circle">
              <div class="block">
                <el-image
                  style="width: 300px; height: 300px"
                  :src="userInfoForm.avatar"
                  :preview-src-list="[userInfoForm.avatar]"
                  class="img"
                >
                </el-image>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <!-- 展示信息 -->
      <div style="position: relative">
        <!-- 名称、性别 -->
        <div>
          <span class="name frame el-icon-s-custom"
            >名称: {{ userInfoForm.nickname }}</span
          >
          <span class="gender frame el-icon-male"
            ><i class="el-icon-female"></i>性别:
            {{
              userInfoForm.gender === 0
                ? "男"
                : userInfoForm.gender === 1
                ? "女"
                : ""
            }}</span
          >
        </div>
        <!-- 邮箱-->
        <div>
          <span class="email frame el-icon-message"
            >邮箱: {{ userInfoForm.email }}</span
          >
        </div>
        <!--手机-->
        <div>
          <span class="phone frame el-icon-mobile-phone"
            >联系方式: {{ userInfoForm.phone }}</span
          >
        </div>
        <!--学院、专业 -->
        <div>
          <span class="col frame el-icon-school">学院: {{ collegeName }}</span>
          <span class="maj frame el-icon-collection"
            >专业: {{ majorName }}</span
          >
        </div>
        <div>
          <span class="create frame el-icon-mobile-phone"
            >注册时间: {{ userInfoForm.gmtCreate }}</span
          >
        </div>
      </div>
    </div>
    <!-- 中间的信息修改 -->
    <!-- 可编辑的表单 -->
    <div class="modFrom">
      <el-form
        ref="userInfoForm"
        :model="userInfoForm"
        label-width="80px"
        v-if="isEditable"
      >
        <el-upload
          class="avatar-uploader"
          :action="actionUrl"
          :show-file-list="false" 
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload" 
          name="file"
          :data="uploadData"
          >
          <img v-if="userInfoForm.avatar" :src="userInfoForm.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <el-form-item label="名称">
          <el-input v-model="userInfoForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="userInfoForm.gender">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="学院">
          <el-select v-model="userInfoForm.collegeId" placeholder="请选择学院">
            <el-option
              v-for="item in collegeAll"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业">
          <el-select
            v-model="userInfoForm.majorId"
            @click="majorData"
            placeholder="请选择专业"
          >
            <el-option
              v-for="item in majorAll"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userInfoForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="userInfoForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="个人介绍">
          <el-input
            type="textarea"
            v-model="userInfoForm.description"
          ></el-input>
        </el-form-item>

      </el-form>
      <!-- 只可读的表单 -->
      <div class="readableFrom">
        <el-form
          ref="userInfoForm"
          :model="userInfoForm"
          label-width="80px"
          disabled="true"
          v-if="!isEditable"
        >
        <el-upload
          class="avatar-uploader"
          :action="actionUrl"
          :show-file-list="false" 
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload" 
          name="file"
          :data="uploadData"
          >
          <img v-if="userInfoForm.avatar" :src="userInfoForm.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
          <el-form-item label="名称">
            <el-input v-model="userInfoForm.nickname" readonly></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="userInfoForm.gender" readonly>
              <el-radio :label="0">男</el-radio>
              <el-radio :label="1">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="学院">
            <el-select
              v-model="userInfoForm.collegeId"
              placeholder="请选择学院"
              readonly
            >
              <el-option
                v-for="item in collegeAll"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="专业">
            <el-select
              v-model="userInfoForm.majorId"
              @click="majorData"
              placeholder="请选择专业"
              readonly
            >
              <el-option
                v-for="item in majorAll"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="userInfoForm.email" readonly></el-input>
          </el-form-item>
          <el-form-item label="手机号码">
            <el-input v-model="userInfoForm.phone" readonly></el-input>
          </el-form-item>
          <el-form-item label="个人介绍" readonly>
            <el-input
              type="textarea"
              v-model="userInfoForm.description"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button class="modbut" @click="toggleEditMode" v-if="!isEditable">修改</el-button>
        <div v-if="isEditable">
          <el-button type="primary" @click="submitForm" class="submitbut"
            >提交</el-button
          >
          <el-button @click="cancelEdit" class="cancebut">取消</el-button>
        </div>
      </div>
    </div>
    <!-- 右侧小地球 -->
     <div class="rotating">
        <rotating-earth/>
     </div>
  </div>
</template>

<script>
import { queryToken } from "@/api/userInformationManagement/queryToken";
import { saveUserInfo } from "@/api/userInformationManagement/saveUserInfo";
import { collegeQueryAll } from "@/api/collegeManagement/queryAll";
import { querCollegeId } from "@/api/major/queryCollegeId";
import RotatingEarth from '@/components/RotatingEarth.vue'
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "userInformation",
  components:{RotatingEarth},
  data() {
    return {
        actionUrl: 'http://42.194.233.38:8222/minioservice/minio-upload/upload', // 服务器上传API地址
      isEditable: false, //控制表单的是否可编辑
      collegeAll: [], // 存储学院区域选项数据
      majorAll: [], // 存储专业区域选项数据
      userInfoForm: {
        avatar: "",
        collegeId: "",
        description: "",
        email: "",
        gender: 1,
        gmtCreate: "",
        gmtModified: "",
        grade: "",
        id: "",
        majorId: "",
        nickname: "",
        openid: "",
        password: "",
        phone: "",
      },
      uploadData: {
        bucketName: 'avatar' // 上传头像时的附加参数
      }
    };
  },
  computed: {
    collegeName() {
      // 根据collegeId找到对应的学院名称
      const college = this.collegeAll.find(
        (c) => c.id === this.userInfoForm.collegeId
      );
      return college ? college.name : "未选择学院"; // 如果找到则返回名称，否则返回默认文本
    },
    majorName() {
      // 根据collegeId找到对应的学院名称
      const major = this.majorAll.find(
        (c) => c.id === this.userInfoForm.majorId
      );
      return major ? major.name : "未选择专业"; // 如果找到则返回名称，否则返回默认文本
    },
  },
  watch: {
    // 监视userInfoForm.collegeId的变化
    "userInfoForm.collegeId": {
      handler(newVal) {
        // 当collegeId变化时，调用majorData方法
        this.majorData(newVal);
      },
    },
  },
  created() {
    this.queryUserInfo();
    this.collegeData();
    if (this.userInfoForm.collegeId) {
      this.majorData();
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      // 可以在这里添加文件类型和大小的校验
      const isImage = file.type.match('image/*');
      if (!isImage) {
        this.$message.error('只能上传图片文件');
      }
      return isImage;
    },
    handleAvatarSuccess(response) {
      // 假设上传成功后，服务器返回图片的URL
      if (response.success) {
        this.userInfoForm.avatar = response.data.url
      } else {
        this.$message.error('上传失败');
      }
    //   uploadFiles({
    //     bucketName:"avatar",
    //     file:file
    //   }).then(res => {
    //     if (res.code === 20000) {
    //         this.userInfoForm.avatar = res.data.url
    //     }else {
    //     this.$message.error('上传失败');
    //   }
    //   })
    },
    toggleEditMode() {
      //控制表单是否可修改
      this.isEditable = !this.isEditable;
      // 如果切换到可编辑状态，可能需要重新加载数据
      if (this.isEditable) {
        // 加载数据的方法
        this.queryUserInfo();
        this.collegeData();
      }
    },
    submitForm() {
      // 表单提交逻辑
      this.$refs.userInfoForm.validate((valid) => {
        if (valid) {
          // 调用API提交数据
          saveUserInfo(this.userInfoForm).then((res) => {
            this.$message({
              message: res.message,
              type: "success",
            });
            this.isEditable = !this.isEditable;
          });
        } else {
          this.$message({
            message: "表单验证失败",
            type: "error",
          });
          return false;
        }
      });
    },
    cancelEdit() {
      // 取消编辑，可能需要重新加载数据或重置表单
      this.queryUserInfo();
      this.collegeData();
      this.isEditable = false;
    },
    queryUserInfo() {
      queryToken().then((res) => {
        console.log(res);
        if (res.code == 20000) {
          this.userInfoForm = res.data.user;
        } else {
          this.$message({
            message: "获取用户信息失败",
            type: "error",
          });
        }
      });
    },
    collegeData() {
      collegeQueryAll()
        .then((res) => {
          console.log(res);
          if (this.userInfoForm.collegeId) {
            this.majorData();
          }
          this.collegeAll = res.data.collegeList.map((item) => ({
            id: item.id,
            name: item.name,
          }));
        })
        .catch((error) => {
          console.error("Error fetching region data:", error);
        });
    },
    majorData(collegeId) {
      // 确保传入学院ID
      if (!collegeId) return;
      querCollegeId(collegeId).then((res) => {
        this.majorAll = res.data.majorList.map((item) => ({
          id: item.id,
          name: item.name,
        }));
      });
    },
  },
};
</script>

<style scoped>
.container {
  position: relative;
}
.img {
  margin-left: 20px;
  margin-top: 20px;
}
.frame {
  border-style: solid;
  border-radius: 30px;
  padding: 10px 30px;
  margin-left: 10px;
}
.name {
  position: absolute;
  left: 10px;
  top: 10px;
}
.gender {
  position: absolute;
  left: 160px;
  top: 10px;
}
.email {
  position: absolute;
  left: 10px;
  top: 60px;
}
.phone {
  position: absolute;
  left: 10px;
  top: 110px;
}
.col {
  position: absolute;
  left: 10px;
  top: 160px;
}
.maj {
  position: absolute;
  left: 10px;
  top: 210px;
}
.create {
  position: absolute;
  left: 10px;
  top: 260px;
}

.modFrom {
  position: absolute;
  width: 300px;
  right: 620px;
  top: 20px;
}
.readableFrom {
  position: absolute;
  width: 300px;
  right: 0;
  top: 0;
}
.modbut {
  position: absolute;
  right: 0;
  top: 525px;
}
.submitbut {
  position: absolute;
  right: 140px;
  top: 525px;
}
.cancebut {
  position: absolute;
  right: 70px;
  top: 525px
}
/* 根据需要添加样式 */
.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
  margin-left: 110px;
}
.avatar-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.rotating{
position: absolute;
width: 585px;
height: 100%;
right: 0;
top: 0;
}
</style>
